<template>
  <view>
    <u-popup
      class="custom-popup"
      v-model="show"
      :zoom="false"
      mode="center"
      width="1048rpx"
      height="740rpx"
      :mask-custom-style="{
        background: 'rgba(0, 0, 0, 0.5)',
      }"
    >
      <view class="mask">
        <view class="mask_title"> 句子朗读测评 </view>
        <view class="mask_sentence">
          <view class="sentence">
            <view class="sentence_title">
              {{ sentenceInfo.sentenceEnglish }}
            </view>
            <view class="sentence_text">
              {{ sentenceInfo.sentenceChinese }}
            </view>
            <view class="sentence_icon">
              <view @click="play(1)">
                <image
                  style="width: 22rpx"
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/fayin.png"
                  mode="widthFix"
                />
              </view>
              <view @click="play(0.8)">
                <image
                  style="width: 27rpx"
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/man.png"
                  mode="widthFix"
                />
              </view>
            </view>
          </view>
        </view>
        <view class="mask_score" v-if="isShowResult">
          <view class="score">
            <view class="score_content">
              <view class="score_num">
                <text>{{ total_score }}分</text>
              </view>
              <view class="score_rate">
                <image
                  v-for="item of grade"
                  :key="item"
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/rate-active.png"
                  mode="scaleToFill"
                />
                <image
                  v-for="item of 5 - grade"
                  :key="item"
                  src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/word/rate.png"
                  mode="scaleToFill"
                />
              </view>
            </view>
            <view class="score_content">
              <view class="score_text">
                <view>准确度：</view>
                <text>{{ accuracy_score }}分</text>
              </view>
              <view class="score_text">
                <view>流畅度：</view>
                <text>{{ fluency_score }}分</text>
              </view>
              <view class="score_text">
                <view>完整度：</view>
                <text>{{ integrity_score }}分</text>
              </view>
              <view class="score_text">
                <view>标准度：</view>
                <text>{{ standard_score }}分</text>
              </view>
            </view>
          </view>
        </view>
        <view class="mask_step">
          <view class="step">
            <template v-if="!isRecording">
              <view class="button">
                <view class="button_content">
                  <view class="button_box" @click="record()">
                    <image
                      src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/bofang.png"
                      mode="scaleToFill"
                    />
                  </view>
                  <view class="button_text"> 单击麦克风并说出 </view>
                </view>
              </view>
            </template>
            <template v-else>
              <view>
                <view class="shape">
                  <RecordShape></RecordShape>
                </view>
                <view class="button">
                  <view class="button_content">
                    <view class="button_box" @click="endRecord()">
                      <image
                        src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/zanting.png"
                        mode="scaleToFill"
                      />
                    </view>
                    <view class="button_text"> 正在录音 {{ countText }} </view>
                  </view>
                </view>
              </view>
            </template>
            <template v-if="isShowResult">
              <view class="button">
                <view class="button_content">
                  <view class="button_box" @click="playVoice()">
                    <image
                      src="https://hengxiao-resource.oss-cn-hangzhou.aliyuncs.com/web/resources/images/hengxiao/common/sound.png"
                      mode="scaleToFill"
                    />
                  </view>
                  <view class="button_text"> 收听 </view>
                </view>
              </view>
            </template>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import permision from "@/js_sdk/wa-permission/permission.js";
import parser from "fast-xml-parser";
const recorderManager = uni.getRecorderManager();

const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;

const englishAudioContext = uni.createInnerAudioContext();
englishAudioContext.autoplay = true;
export default {
  props: {
    sentenceInfo: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      isIos: true,
      voicePath: "",
      recordOptions: {
        duration: 60000,
        sampleRate: 16000,
        encodeBitRate: 48000,
      },
      permisionIosMap: {
        location: "位置",
        camera: "摄像头",
        photoLibrary: "相册",
        record: "麦克风",
        push: "推送",
        contact: "通讯录",
        calendar: "日历",
        memo: "备忘录",
      },
      permisionAndroidMap: {
        "android.permission.ACCESS_FINE_LOCATION": "位置",
        "android.permission.ACCESS_COARSE_LOCATION": "模糊位置",
        "android.permission.CAMERA": "摄像头",
        "android.permission.READ_EXTERNAL_STORAGE": "外部存储(含相册)读取",
        "android.permission.WRITE_EXTERNAL_STORAGE": "外部存储(含相册)写入",
        "android.permission.RECORD_AUDIO": "麦克风",
        "android.permission.READ_CONTACTS": "通讯录读取",
        "android.permission.WRITE_CONTACTS": "通讯录写入",
        "android.permission.READ_CALENDAR": "日历读取",
        "android.permission.WRITE_CALENDAR": "日历写入",
        "android.permission.READ_SMS": "短信读取",
        "android.permission.SEND_SMS": "短信发送",
        "android.permission.RECEIVE_SMS": "接收新短信",
        "android.permission.READ_PHONE_STATE": "获取手机识别码等信息的",
        "android.permission.CALL_PHONE": "拨打电话",
        "android.permission.READ_CALL_LOG": "获取通话记录",
      },
      isCanClick: true,
      isRecording: false,
      isShowResult: false,
      senconds: 0,
      countText: "",
      accuracy_score: 0, //准确度评分
      fluency_score: 0, //流畅度评分
      integrity_score: 0, //完整度评分
      standard_score: 0, //标准度评分
      total_score: 0, //篇章总分
      grade: 0,
      show: false,
    };
  },
  mounted() {
    // #ifdef APP-PLUS
    this.isIos = plus.os.name == "iOS";
    // #endif
    let self = this;
    recorderManager.onStop(function (res) {
      self.voicePath = res.tempFilePath;
      self.uploadVoice();
    });
  },
  methods: {
    open() {
      this.show = true;
    },
    back() {
      this.show = false;
    },
    initSentence() {
      this.isShowResult = false;
      this.senconds = 0;
    },
    record() {
      if (!this.isCanClick) return;
      this.isCanClick = false;
      if (this.isShowResult) {
        this.initSentence();
      }
      if (this.isIos) {
        this.judgeIosPermission("record");
      } else {
        this.requestAndroidPermission("android.permission.RECORD_AUDIO");
      }
    },
    judgeIosPermission: function (permisionID) {
      var result = permision.judgeIosPermission(permisionID);
      var strStatus = result ? "已" : "未";
      if (!result) {
        uni.showModal({
          title: "",
          content:
            this.permisionIosMap[permisionID] +
            "权限" +
            strStatus +
            "获得授权,是否去开启？",
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              plus.runtime.openURL("app-settings://");
            }
          },
        });
      } else {
        this.startRecord();
      }
    },
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      var strStatus;
      if (result == 1) {
        strStatus = "已获得授权";
        this.startRecord();
      } else if (result == 0) {
        strStatus = "未获得授权";
      } else {
        strStatus = "被永久拒绝权限";
        uni.showModal({
          title: "",
          content: this.permisionAndroidMap[permisionID] + "权限" + strStatus,
          showCancel: false,
        });
      }
    },
    startRecord() {
      recorderManager.start(this.recordOptions);
      this.isRecording = true;
      this.countText = "00:00";
      this.countInterval = setInterval(() => {
        this.senconds++;
        let second = this.senconds - Math.floor(this.senconds / 60) * 60;
        second < 10 ? (second = "0" + second) : "";
        this.countText = "0" + Math.floor(this.senconds / 60) + ": " + second;
        if (this.senconds >= 60) {
          this.isRecording = false;
          this.endRecord();
          clearInterval(this.countInterval);
        }
      }, 1000);
    },
    endRecord() {
      recorderManager.stop();
      clearInterval(this.countInterval);
      this.second = 0;
      this.minute = 0;
      this.isRecording = false;
    },
    playVoice() {
      if (this.voicePath) {
        innerAudioContext.src = this.voicePath;
        innerAudioContext.play();
      }
    },
    uploadVoice() {
      this.$upload(this.voicePath, {
        wordText: 'word',
      }).then((res) => {
        let xml = res.data;
        let grade = parser.parse(xml, {
          attributeNamePrefix: "",
          ignoreAttributes: false,
        });
        if (grade) {
          let read_chapter =
            grade.xml_result.read_sentence.rec_paper.read_chapter;
          this.accuracy_score = parseInt(read_chapter.accuracy_score);
          this.fluency_score = parseInt(read_chapter.fluency_score);
          this.integrity_score = parseInt(read_chapter.integrity_score);
          this.standard_score = parseInt(read_chapter.standard_score);
          this.total_score = parseInt(read_chapter.total_score);
          if (this.total_score === 0) {
            this.grade = 0;
          } else if (this.total_score <= 20) {
            this.grade = 1;
          } else if (this.total_score <= 40) {
            this.grade = 2;
          } else if (this.total_score <= 60) {
            this.grade = 3;
          } else if (this.total_score <= 80) {
            this.grade = 4;
          } else if (this.total_score <= 100) {
            this.grade = 5;
          }
          this.isShowResult = true;
          this.isCanClick = true;
          this.saveRecord();
        }
      });
    },
    play(speed) {
      if (!englishAudioContext.paused) return;
      englishAudioContext.src = this.sentenceInfo.sentenceAudio
        ? this.sentenceInfo.sentenceAudio
        : this.sentenceInfo.usAudio;
      englishAudioContext.playbackRate = speed;
      englishAudioContext.play();
    },
    saveRecord() {},
  },
};
</script>

<style lang="scss" scoped>
@import "./SentenceReadingEvaluation";
</style>
